using System;
using System.Collections.Generic;
using System.Web;
using BBX.Common;
using BBX.Config;
using BBX.Entity;
using BBX.Forum;
using BBX.Web.UI;

namespace BBX.Web
{
    public class showtopic : TopicPage
    {
        public List<Post> postlist = new List<Post>();
        //public PollInfo pollinfo = new PollInfo();
        public Poll pollinfo = new Poll();
        public Boolean showpollresult = true;
        public Dictionary<Int32, Int32> debateList = new Dictionary<Int32, Int32>();
        public Debate debateexpand = new Debate();
        //public string goodscategoryfid = (GeneralConfigInfo.Current.Enablemall <= 0) ? "{}" : MallPluginProvider.GetInstance().GetGoodsCategoryWithFid();
        public UserExtcreditsInfo userextcreditsinfo = new UserExtcreditsInfo();
        //public List<PrivateMessageInfo> pmlist = new List<PrivateMessageInfo>();
        public List<BonusLog> bonuslogs = new List<BonusLog>();
        public Int32 posterid = DNTRequest.GetInt("posterid", 0);
        public String nextpage = "";
        public String listlink = "";
        public String navhomemenu = "";
        public IXForum[] visitedforums = Forums.GetVisitedForums();
        public Boolean showvisitedforumsmenu;
        private IUser userInfo;
        public Int32 hide;
        public Int32 typeid = DNTRequest.GetInt("typeid", -1);
        public Int32 stand = DNTRequest.GetInt("stand", 0);
        public Int32 invisible = DNTRequest.GetInt("invisible", 0);
        public String[] postleftshow;
        public String[] userfaceshow;

        protected override void ShowPage()
        {
            topic = base.GetTopicInfo();
            if (topic == null)
            {
                return;
            }
            topicid = topic.ID;
            forumid = topic.Fid;
            forum = Forums.GetForumInfo(forumid);
            if (forum == null)
            {
                base.AddErrLine("不存在的版块ID");
                return;
            }
            if (!base.ValidateInfo() || base.IsErr())
            {
                return;
            }
            base.IsModer();
            var topicPrice = GetTopicPrice(topic);
            if (topic.Special == 0 && topicPrice > 0)
            {
                HttpContext.Current.Response.Redirect(forumpath + "buytopic.aspx?topicid=" + topic.ID);
                return;
            }
            if (postid > 0 && Post.FindByID(postid) == null)
            {
                base.AddErrLine("该帖可能已被删除 " + string.Format("<a href=\"{0}\">[返回主题]</a>", base.ShowTopicAspxRewrite(topicid, 1)));
                return;
            }
            ForumUtils.SetVisitedForumsCookie(forumid.ToString());
            if (userid > 0)
            {
                userInfo = BBX.Entity.User.FindByID(userid);
            }
            if (topic.Identify > 0)
            {
                topicidentify = TopicIdentify.FindByID(topic.Identify);
            }
            pagetitle = string.Format("{0} - {1}", topic.Title, Utils.RemoveHtml(forum.Name));
            base.GetForumAds(forum.Fid);
            TopicType.GetTopicTypeArray().TryGetValue(topic.TypeID, out topictypes);
            topictypes = (topictypes.IsNullOrEmpty() ? "" : ("[" + topictypes + "]"));
            userextcreditsinfo = Scoresets.GetScoreSet(Scoresets.GetTopicAttachCreditsTrans());
            score = Scoresets.GetValidScoreName();
            scoreunit = Scoresets.GetValidScoreUnit();
            navhomemenu = Caches.GetForumListMenuDivCache(usergroupid, userid, config.Extname);
            base.EditorState();
            var array = config.Customauthorinfo.Split('|');
            postleftshow = array[0].Split(',');
            userfaceshow = array[1].Split(',');
            onlyauthor = ((onlyauthor == "1" || onlyauthor == "2") ? onlyauthor : "0");
            BindPageCountAndId();
            base.GetPostAds(GetPostPramsInfo(topicPrice), postlist.Count);
            //this.bonuslogs = Bonus.GetLogs(this.topic);
            if (topic.Special == 3) bonuslogs = BonusLog.GetLogs(topic.ID);
            if (topic.Special == 1)
            {
                GetPollInfo();
            }
            if (topic.Special == 4)
            {
                GetDebateInfo();
            }
            enabletag = config.Enabletag && forum.AllowTag;
            if (postlist != null && postlist.Count > 0)
            {
                base.UpdateMetaInfo(Utils.RemoveHtml(postlist[0].Message));
            }
            IsGuestCachePage();
            //Topic.UpdateViewCount(this.topicid, 1);
            topic.Views++;
            topic.SaveAsync(10000);
            Topics.MarkOldTopic(topic);
            topicviews = topic.Views;
            Online.UpdateAction(olid, UserAction.ShowTopic, forumid, forum.Name, topicid, topic.Title);
            if (DNTRequest.GetInt("fromfav", 0) > 0)
            {
                //Favorites.UpdateUserFavoriteViewTime(this.userid, this.topicid);
                var fav = Favorite.FindByUidAndTid(userid, topicid);
                if (fav != null)
                {
                    fav.ViewTime = DateTime.Now;
                    fav.Update();
                }
            }
        }

        public void IsGuestCachePage()
        {
            if (userid == -1 && pageid > 0 && pageid < pagecount && ForumUtils.IsGuestCachePage(pageid, "showtopic"))
            {
                isguestcachepage = 1;
            }
        }

        public void GetPollInfo()
        {
            var pi = Poll.FindByTid(topic.ID);
            if (pi == null) return;

            pollinfo = pi;

            voters = misc.GetVoters(topicid, userid, username, out allowvote);
            if (pollinfo.Uid != userid && useradminid != 1 && pollinfo.Visible == 1 && (allowvote || (userid == -1 && !Utils.InArray(topicid.ToString(), ForumUtils.GetCookie("polled")))))
            {
                showpollresult = false;
            }
            if (pollinfo.Expiration <= DateTime.MinValue)
            {
                pollinfo.Expiration = DateTime.Now;
            }
            if (pollinfo.Expiration < DateTime.Now)
            {
                allowvote = false;
            }
        }

        public void GetDebateInfo()
        {
            debateexpand = Debate.FindByTid(topicid);
            debateList = Debates.GetPostDebateList(topicid);
            if (debateexpand.Terminaled)
            {
                isenddebate = true;
                if (isenddebate)
                {
                    canreply = false;
                }
            }
            foreach (var item in postlist)
            {
                if (debateList != null && debateList.ContainsKey(item.ID))
                {
                    item.Debateopinion = debateList[item.ID];
                }
            }
        }

        public Int32 GetTopicPrice(Topic topicInfo)
        {
            var result = 0;
            if (topicInfo.Special == 0 && topicInfo.Price > 0 && userid != topicInfo.PosterID && ismoder != 1)
            {
                result = topicInfo.Price;
                var max = Scoresets.GetMaxChargeSpan();
                if (PaymentLog.IsBuyer(topicInfo.ID, userid) || max != 0 && topicInfo.PostDateTime.AddHours(max) < DateTime.Now)
                {
                    result = -1;
                }
            }
            return result;
        }

        public PostpramsInfo GetPostPramsInfo(Int32 price)
        {
            var pi = new PostpramsInfo();
            pi.Fid = forum.Fid;
            pi.Tid = topicid;
            pi.Jammer = forum.Jammer;
            pi.Pagesize = ppp;
            pi.Pageindex = pageid;
            pi.Getattachperm = forum.Getattachperm;
            pi.Usergroupid = usergroupid;
            pi.Attachimgpost = config.Attachimgpost;
            pi.Showattachmentpath = config.Showattachmentpath;
            pi.Price = price;
            pi.Usergroupreadaccess = ((ismoder == 1) ? 0x7FFFFFFF : usergroupinfo.Readaccess);
            pi.CurrentUserid = userid;
            pi.Showimages = forum.Allowimgcode;
            pi.Smiliesinfo = Smilies.GetSmiliesListWithInfo();
            pi.Customeditorbuttoninfo = Editors.GetCustomEditButtonListWithInfo();
            pi.Smiliesmax = config.Smiliesmax;
            pi.Bbcodemode = config.Bbcodemode;
            pi.CurrentUserGroup = usergroupinfo;
            //pi.Topicinfo = this.topic.Cast<TopicInfo>();
            pi.Hide = ((topic.Hide >= 1) ? ((ismoder == 1 || Post.IsReplier(topicid, userid)) ? -1 : topic.Hide) : topic.Hide);
            pi.Hide = ((topic.PosterID == userid) ? -2 : pi.Hide);
            hide = pi.Hide;
            pi.Condition = Posts.GetPostPramsInfoCondition(onlyauthor, topicid, posterid);
            pi.TemplateWidth = Template.GetWidth(templatepath);
            pi.Usercredits = ((userInfo == null) ? 0 : userInfo.Credits);
            pi.Invisible = invisible;
            switch (stand)
            {
                case 0:
                    postlist = Posts.GetPostList(pi, out attachmentlist, ismoder == 1);
                    break;

                case 1:
                    postlist = Debates.GetPositivePostList(pi, out attachmentlist, ismoder == 1);
                    break;

                case 2:
                    postlist = Debates.GetNegativePostList(pi, out attachmentlist, ismoder == 1);
                    break;
            }
            if (topic.Special == 4)
            {
                var text = "";
                foreach (var item in postlist)
                {
                    text = text + item.ID + ",";
                }
                var postDiggs = Debates.GetPostDiggs(text.Trim(','));
                foreach (var item in postlist)
                {
                    if (postDiggs.ContainsKey(item.ID))
                    {
                        item.Diggs = postDiggs[item.ID];
                    }
                }
            }
            if (postlist.Count == 0)
            {
                TopicAdmins.RepairTopicList(topicid.ToString());
                topic = base.GetTopicInfo();
                BindPageCountAndId();
                pi.Pageindex = pagecount;
                postlist = Posts.GetPostList(pi, out attachmentlist, ismoder == 1);
            }
            foreach (var current3 in attachmentlist)
            {
                if (Forums.AllowGetAttachByUserID(forum.Permuserlist, userid))
                {
                    current3.Getattachperm = 1;
                    current3.AllowRead = true;
                }
            }
            base.BindDownloadAttachmentTip();
            return pi;
        }

        public new void BindPageCountAndId()
        {
            base.BindPageCountAndId();
            var text = (typeid == -1) ? "" : ("&typeid=" + typeid);
            var text2 = (stand == 0) ? "" : ("&stand=" + stand);
            var text3 = (string.IsNullOrEmpty(onlyauthor) || onlyauthor == "0") ? "" : "onlyauthor=" + onlyauthor + "&posterid=" + posterid;
            if (onlyauthor.IsNullOrEmpty() || onlyauthor == "0")
            {
                if (config.Aspxrewrite == 1 && typeid <= -1 && stand == 0)
                {
                    pagenumbers = Utils.GetStaticPageNumbers(pageid, pagecount, "showtopic-" + topicid, config.Extname, 8);
                }
                else
                {
                    pagenumbers = Utils.GetPageNumbers(pageid, pagecount, string.Format("showtopic.aspx?topicid={0}{1}{2}", topicid, text, text2), 8);
                }
            }
            else
            {
                pagenumbers = Utils.GetPageNumbers(pageid, pagecount, string.Format("showtopic.aspx?topicid={0}&{1}{2}", topicid, text3, text), 8);
            }
            if (pageid != pagecount)
            {
                if (stand != 0)
                {
                    nextpage = string.Format("<a href=\"showtopic.aspx?topicid={0}{1}{2}&page={3}\" class=\"next\">下一页</a>", new Object[]
                    {
                        topicid,
                        text,
                        text2,
                        pageid + 1
                    });
                }
                else
                {
                    var text4 = Urls.ShowTopicAspxRewrite(topicid, pageid + 1, typeid);
                    var text5 = (String.IsNullOrEmpty(text3)) ? "" : ((text4.IndexOf("?") == -1) ? "?" : "&");
                    nextpage = "<a href=\"" + text4 + text5 + text3 + "\" class=\"next\">下一页</a>";
                }
            }
            showvisitedforumsmenu = (visitedforums != null && ((visitedforums.Length == 1 && visitedforums[0].Fid != forumid) || visitedforums.Length > 1));
            if (typeid < 0)
            {
                listlink = "<a id=\"visitedforums\" href=\"" + Urls.ShowForumAspxRewrite(forumid, forumpid, forum.Rewritename) + "\"";
            }
            else
            {
                listlink = "<a id='visitedforums' href=showforum.aspx?forumid=" + forumid + "&page=" + forumpid + "&typeid=" + typeid;
            }
            if (showvisitedforumsmenu)
            {
                listlink += " onmouseover=\"$('visitedforums').id = 'visitedforumstmp';this.id = 'visitedforums';showMenu({'ctrlid':this.id, 'pos':'34'})\";";
            }
            listlink += ">返回列表</a>";
            if (String.IsNullOrEmpty(onlyauthor) || onlyauthor == "0")
            {
                ForumUtils.WriteCookie("referer", string.Format("showtopic.aspx?topicid={0}&page={1}", topicid, pageid));
                return;
            }
            ForumUtils.WriteCookie("referer", "showtopic.aspx?&topicid=" + topicid + "&" + text3 + "&page=" + pageid);
        }
    }
}